package com.wzgl.core.controller;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheName;
import com.wzgl.core.CacheConsts;
import com.wzgl.core.base.JBaseCRUDController;
import com.wzgl.core.interceptor.RequiredUserIdInterceptor;
import com.wzgl.core.model.Tdicinfo;
import com.wzgl.core.model.Tdicsort;
import com.wzgl.core.model.Tdirection;
import com.wzgl.core.model.Tgrid;
import com.wzgl.core.model.TgridResult;
import com.wzgl.core.model.Tmagic;
import com.wzgl.core.model.TsendLogo;
import com.wzgl.core.model.Tusers;
import com.wzgl.core.server.GirdService;
import com.wzgl.core.server.SendLogoService;
import com.wzgl.core.server.TdicinfoService;
import com.wzgl.core.utils.StringUtils;
import com.wzgl.core.utils.UuidUtil;
import com.wzgl.core.utils.WZGLUtils;
import com.wzgl.core.utils.WebUtils;
import com.wzgl.core.webmagic.utils.PinyinUtils;
import com.wzgl.core.xny.model.TnewextendsXny;
import com.wzgl.core.xny.model.TnewsXny;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class GridController extends JBaseCRUDController<Tgrid> {
	private Log log=Log.getLog(GridController.class);
	GirdService gs = Duang.duang(GirdService.class);
	TdicinfoService tdicinfo = Duang.duang(TdicinfoService.class);
	
	//到发布新的格子
	@Before(RequiredUserIdInterceptor.class)
	public void toNewGrid() throws Exception {
		String fid = getPara("fid");
		/***
		 * 如何FID不为空 则修改
		 */
		if(StringUtils.isNotEmpty(fid)){
			Tgrid g= Tgrid.dao.findById(fid);
			setAttr("tgrid",g);
		}
		//分类字典
		List<Tdicinfo> tdic = Tdicinfo.dao.getTdicBySort(PropKit.use("wzgl_tdinc_conts.txt").get("tdic_wzlx"));
		setAttr("tdicinfo",tdic);
		
		render("gridOper.jsp");
	}
	
	@Before(RequiredUserIdInterceptor.class)
	public void grid_index() throws Exception{
		List<Tdicinfo> sorts = Tdicinfo.dao.getAll();
		setAttr("sorts", sorts);
		render("grid_list.jsp");
	}
	
	@Before(RequiredUserIdInterceptor.class)
	public void grid_recommend() throws Exception{
		render("grid_recommend.jsp");
	}
	@Before(RequiredUserIdInterceptor.class)
	public void grid_up(){
		List<Tdicinfo> tdic = Tdicinfo.dao.getTdicBySort(PropKit.use("wzgl_tdinc_conts.txt").get("tdic_wzlx"));
		setAttr("tdic", tdic);
		render("grid_up.jsp");
	}
	/***
	 * 文章移除
	 * @throws Exception
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void grid_del() throws Exception{
		final String fid = getPara("fid");
		final Tgrid tgrid= Tgrid.dao.findById(fid);
		tgrid.setFstatus(-1);
		boolean b = false;
		  b = Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					
					if(StringUtils.isNotEmpty(tgrid.getFid())){
						if (!tgrid.update()) {
							return false;
						}
					}else{
						if (!tgrid.save()) {
							return false;
						}
					}
					tgrid.putCache(tgrid.getFid(),tgrid);
					return true;
				}
			});
		if(b){
			renderAjaxResultForSuccess("文章删除");
		}else{
			renderAjaxResultForError("删除失败");
		}
	}
	/***
	 * 首页轮播
	 * @throws Exception
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void grid_ftop() throws Exception{
		
	}
	public void grid_view() throws Exception{
		String fid = getPara("fid");
		String view = "";
		if(!StrKit.isBlank(fid)){
			Tgrid g= Tgrid.dao.findById(fid);
			Tmagic m = Tmagic.dao.findById(g.getFmzgicId());
			//获取模板
			if(m != null && !StrKit.isBlank(m.getFmodel())){
				view = m.getFmodel();
			}
			setAttr("grid", g);
		}
		render(view);
	}
	/***
	 * 获取已审核数据
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void toResutList() throws Exception{
		Page<TgridResult> list_page;
		try {
			BigInteger page=getParaToBigInteger("page",BigInteger.valueOf(1));
			BigInteger pagesize=getParaToBigInteger("pagesize",BigInteger.valueOf(10));
			String fvalue =  getParaTo("fvalue");
			Integer fstatus =  getParaToInt("fstatus");
			String ftype =  getPara("ftype");
			TgridResult t = getModel(TgridResult.class);
			t.setFstatus(fstatus);
			t.setFtitle(fvalue);
			t.setFtype(ftype);
			list_page= TgridResult.dao.paginateByObj(page.intValue(),pagesize.intValue(),t);
			renderAjaxResult("",0,list_page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderAjaxResultForError(e.getMessage());
		}
	}
	//获取格子列表
	@Before(RequiredUserIdInterceptor.class)
	public void toGridList() throws Exception{
		Page<Tgrid> list_page;
		try {
			BigInteger page=getParaToBigInteger("page",BigInteger.valueOf(1));
			BigInteger pagesize=getParaToBigInteger("pagesize",BigInteger.valueOf(10));
			String ftitle =  getParaTo("fvalue");
			Integer fstatus =  getParaToInt("fstatus");
			String fmzgicId =  getParaTo("fmzgicId");
			Tgrid t = getModel(Tgrid.class);
			t.setFstatus(fstatus);
			t.setFtitle(ftitle);
			t.setFmzgicId(fmzgicId);
			list_page= Tgrid.dao.paginate(page.intValue(),pagesize.intValue(),t);
			renderAjaxResult("",0,list_page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderAjaxResultForError(e.getMessage());
		}
	}
	
	//通过分类获取格子列表
	@Before(RequiredUserIdInterceptor.class)
	public void grid_list() throws Exception{
		Page<Tgrid> list_page;
		try {
			BigInteger page=getParaToBigInteger("page",BigInteger.valueOf(1));
			BigInteger pagesize=getParaToBigInteger("pagesize",BigInteger.valueOf(10));
			String ftitle =  getParaTo("fvalue");
			Integer fstatus =  getParaToInt("fstatus");
			String fmzgicId =  getParaTo("fmzgicId");
			String ftype =  getParaTo("fsortcode");
			Tgrid t = getModel(Tgrid.class);
			
			t.setFstatus(fstatus);
			t.setFtitle(ftitle);
			t.setFmzgicId(fmzgicId);
			t.setFtype(ftype);
			list_page= Tgrid.dao.paginate(page.intValue(),pagesize.intValue(),t);
			renderAjaxResult("",0,list_page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderAjaxResultForError(e.getMessage());
		}
	}
		
	//文章编辑
	@Before(RequiredUserIdInterceptor.class)
	public void saveGrid(){
		final Tgrid tgrid = getModel(Tgrid.class,"");
		final Tusers user = WebUtils.currentUser(this);
		tgrid.setFuserId(user.getFid());
		Ret ret = new Ret();
		try {
			ret = gs.saveGrid(tgrid,WebUtils.currentUser(this));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			ret = ret.fail("msg", "文章编辑失败,请联系管理员!");
			e.printStackTrace();
		}
		renderJson(ret);
	}
	
	//取消审核
	@Before(RequiredUserIdInterceptor.class)
	public void gridCancle(){
		final String fid = getPara("fid");
		final Tgrid tgrid= Tgrid.dao.findById(fid);
		Ret ret = new Ret();
		try {
			ret = gs.canleGrid(tgrid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			ret = ret.fail("msg", "文章审核失败,请联系管理员!");
			e.printStackTrace();
		}
		renderJson(ret);
	}
	
	//添加到批量操作列表
	@SuppressWarnings("static-access")
	public void batch_add(){
		String fid =  getPara("fid");
		Tgrid tgrid= Tgrid.dao.findById(fid);
		Ret ret = new Ret();
		try {
			ret = ret.set("t", tgrid);
			ret.setOk();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			ret = ret.fail("msg", "添加失败,请联系管理员!");
			e.printStackTrace();
		}
		renderJson(ret);
	}
	
	/**
	 * 批量发布
	 * @throws BadHanyuPinyinOutputFormatCombination 
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void batch_sendBatch() throws BadHanyuPinyinOutputFormatCombination{
		String [] arr = getRequest().getParameterValues("ids");
		//String [] arrto = getRequest().getParameterValues("tos");
		String [] arrto = {"942游戏"};
		Ret ret1 = new Ret();
		Ret ret2 = new Ret();
		Ret ret = new Ret();
		
		ret.set("errorCode", "0");   //初始化
		int sendnum = 0;
		for(String id : arr){
			final String fid = id.substring(2);
			final TgridResult tgrid= TgridResult.dao.findById(fid);
			TgridResult gridresult = TgridResult.dao.findById(fid);
			for(String logoid : arrto){
				
				//查询如果此文章id和去向id都已存在sendlogo表中则不给执行以下操作。
				String deriction_id = logoid; 
				TsendLogo tlogo = TsendLogo.dao.findLogoByGidAndDid(tgrid.getFid(),deriction_id);
				Tdirection tdirect = Tdirection.dao.findById(deriction_id);
				
				if(tlogo == null){
					//加事物
					//日志表保存 对应关系TnewsXny.id  TnewsXny TnewextendsXny
					TnewsXny news = new TnewsXny();
					TnewextendsXny ext = new TnewextendsXny();
					String newsId = "";
					String newsExtendsId = "";
					
					ret1 = new GirdService().saveTnews(news,tgrid,tdirect);
					if(ret1.isOk()){
						ret2 = new GirdService().saveTnewExtends(ext,tgrid,news,tdirect);
						if(ret2.isOk()){
							newsId = ret1.getStr("newsId");
							newsExtendsId = ret2.getStr("newsExtendsId");
							
							//存入数据库
							TsendLogo logo = new TsendLogo();
							logo.setFtnews_id(newsId);
							logo.setFtnewsex_id(newsExtendsId);
							logo.setFid(UuidUtil.get32UUID());
							logo.setFgrid_id(tgrid.getFid());
							logo.setFdirection_id(deriction_id);
							logo.setFsendtime(new Date());
							if(new SendLogoService().addSendLogo(logo).isOk()){
								//加入日志缓存
								String cacheName = CacheConsts.CACHE_SENDED_LOG_NAME;
								String name = CacheConsts.CACHE_SENDED_LOG_NAME+":"+logo.getFid();
								String value = logo.toJson();
								WZGLUtils.setCache(cacheName, name, value);
								//改变上传状态	
								gridresult.setFareadySend(tdirect.getFid());
								gridresult.update();
							}else{
								throw new RuntimeException("保存日志缓存失败");
							}
							sendnum++;
						}
					}else{
						ret.set("errorCode", "2");
					}
				}else{
					ret.set("errorCode", "2");
				}
			}
		}
		ret.set("num", sendnum);
		renderJson(ret);
	}
	
	/***
	 * 发布   
	 * @throws BadHanyuPinyinOutputFormatCombination 
	 */
	@Before(RequiredUserIdInterceptor.class)
	public void grid_send() throws BadHanyuPinyinOutputFormatCombination{
		final String fid = getPara("fid");
		final TgridResult tgrid= TgridResult.dao.findById(fid);
		TgridResult gridresult = TgridResult.dao.findById(fid);
		Ret ret1 = new Ret();
		Ret ret2 = new Ret();
		Ret ret = new Ret();
		
		//String [] arr = getRequest().getParameterValues("tos");
		String [] arr = {"942游戏"};
		for(String logoid : arr){
			//查询如果此文章id和去向id都已存在sendlogo表中则不给执行以下操作。
			String deriction_id = logoid; 
			TsendLogo tlogo = TsendLogo.dao.findLogoByGidAndDid(tgrid.getFid(),deriction_id);
			Tdirection tdirect = Tdirection.dao.findById(deriction_id);
			
			if(tlogo == null){
				//加事物
				//日志表保存 对应关系TnewsXny.id  TnewsXny TnewextendsXny
				TnewsXny news = new TnewsXny();
				TnewextendsXny ext = new TnewextendsXny();
				String newsId = "";
				String newsExtendsId = "";
				
				ret1 = new GirdService().saveTnews(news,tgrid,tdirect);
				if(ret1.isOk()){
					ret2 = new GirdService().saveTnewExtends(ext,tgrid,news,tdirect);
					if(ret2.isOk()){
						newsId = ret1.getStr("newsId");
						newsExtendsId = ret2.getStr("newsExtendsId");
						
						//日志存入数据库
						TsendLogo logo = new TsendLogo();
						logo.setFtnews_id(newsId);
						logo.setFtnewsex_id(newsExtendsId);
						logo.setFid(UuidUtil.get32UUID());
						logo.setFgrid_id(tgrid.getFid());
						logo.setFdirection_id(deriction_id);
						logo.setFsendtime(new Date());
						if(new SendLogoService().addSendLogo(logo).isOk()){
							//加入日志缓存
							String cacheName = CacheConsts.CACHE_SENDED_LOG_NAME;
							String name = CacheConsts.CACHE_SENDED_LOG_NAME+":"+logo.getFid();
							String value = logo.toJson();
							WZGLUtils.setCache(cacheName, name, value);
							//改变上传状态	
							gridresult.setFareadySend(tdirect.getFid());
							gridresult.update();
						}else{
							throw new RuntimeException("保存日志缓存失败");
						}
						ret.set("errorCode", "0");
						ret.set("toWhere", tdirect.getFid());
					}
				}else{
					ret.set("message", "数据上传失败!");
					ret.set("errorCode", "2");
					renderJson(ret);
				}
			}else{
				ret.set("message", "该文章已经上传到"+tdirect.getFname());
				ret.set("errorCode", "2");
				renderJson(ret);
			}
		}
		renderJson(ret);
	}
}
